package com.jy.appmarket.screenlock.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.screenlock.prefs.LockPrefs;
import com.jy.appmarket.screenlock.utils.PatternLockerUtils;
import com.jy.appmarket.screenlock.view.PatternLockerView;
import com.jy.appmarket.screenlock.view.PatternLockerView.Cell;
import com.jy.appmarket.screenlock.view.PatternLockerView.DisplayMode;

import com.umeng.analytics.MobclickAgent;

/**
 * 类说明：
 * 
 * @author kalui.huang
 * @date 2015-2-9
 * @version 1.0
 */
public class SetPatternPasswordActivity extends Activity {
	private static final String KEY_UI_STAGE = "uiStage";
	private static final String KEY_PATTERN_CHOICE = "chosenPattern";
	private PatternLockerView mLockPatternView;
	protected TextView mHeaderText;
	protected List<PatternLockerView.Cell> mChosenPattern = null;
	private Toast mToast;
	private Stage mUiStage = Stage.Introduction;

	public static void startSetPatternPasswordActivity(Context context) {
		Intent intent = new Intent(context, SetPatternPasswordActivity.class);
		context.startActivity(intent);
	}

	protected enum Stage {
		Introduction(R.string.lockpattern_recording_intro_header, true), ChoiceTooShort(
				R.string.lockpattern_recording_incorrect_too_short,
				true), FirstChoiceValid(R.string.lockpattern_pattern_entered_header, false), NeedToConfirm(
						R.string.lockpattern_need_to_confirm,
						true), ConfirmWrong(R.string.lockpattern_need_to_unlock_wrong,
								true), ChoiceConfirmed(R.string.lockpattern_pattern_confirmed_header, false);

		Stage(int headerMessage, boolean patternEnabled) {
			this.headerMessage = headerMessage;
			this.patternEnabled = patternEnabled;
		}

		final int headerMessage;
		final boolean patternEnabled;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_pattern_password);
		initTitle();
		initView(savedInstanceState);
	}

	private void initTitle() {

		ActionBar actionBar = getActionBar();
		actionBar.setTitle("图案密码");
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	private void initView(Bundle savedInstanceState) {
		mLockPatternView = findViewById(R.id.fragment_locker_view);
		mHeaderText = findViewById(R.id.fragment_pattern_hint);
		mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
		if (LockPrefs.getTouchSoundFeedback(this)) {
			mLockPatternView.setTactileFeedbackEnabled(true);
		} else {
			mLockPatternView.setTactileFeedbackEnabled(false);
		}
		if (savedInstanceState == null) {
			updateStage(Stage.Introduction);
		} else {
			// restore from previous state
			final String patternString = savedInstanceState.getString(KEY_PATTERN_CHOICE);
			if (patternString != null) {
				mChosenPattern = PatternLockerUtils.stringToPattern(patternString);
			}
			updateStage(Stage.values()[savedInstanceState.getInt(KEY_UI_STAGE)]);
		}
	}

	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			mLockPatternView.clearPattern();
		}
	};

	protected PatternLockerView.OnPatternListener mChooseNewLockPatternListener = new PatternLockerView.OnPatternListener() {

		public void onPatternStart() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
			patternInProgress();
		}

		public void onPatternCleared() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
		}

		public void onPatternDetected(List<PatternLockerView.Cell> pattern) {
			if (pattern == null)
				return;
			if (mUiStage == Stage.NeedToConfirm) {// || mUiStage ==
													// Stage.ConfirmWrong) {
				if (mChosenPattern == null)
					throw new IllegalStateException("null chosen pattern in stage 'need to confirm");
				if (mChosenPattern.equals(pattern)) {
					updateStage(Stage.ChoiceConfirmed);
				} else {
					updateStage(Stage.ConfirmWrong);
				}
			} else if (mUiStage == Stage.Introduction || mUiStage == Stage.ChoiceTooShort
					|| mUiStage == Stage.ConfirmWrong) {
				if (pattern.size() < PatternLockerUtils.MIN_LOCK_PATTERN_SIZE) {
					updateStage(Stage.ChoiceTooShort);
				} else {
					mChosenPattern = new ArrayList<PatternLockerView.Cell>(pattern);
					updateStage(Stage.NeedToConfirm);
				}
			} else {
				throw new IllegalStateException("Unexpected stage " + mUiStage + " when " + "entering the pattern.");
			}
		}

		public void onPatternCellAdded(List<Cell> pattern) {

		}

		private void patternInProgress() {
			mHeaderText.setText(R.string.lockpattern_recording_inprogress);
		}
	};

	private void updateStage(Stage stage) {
		mUiStage = stage;
		if (stage == Stage.ChoiceTooShort) {
			mHeaderText
					.setText(getResources().getString(stage.headerMessage, PatternLockerUtils.MIN_LOCK_PATTERN_SIZE));
		} else {
			mHeaderText.setText(stage.headerMessage);
		}
		// same for whether the patten is enabled
		if (stage.patternEnabled) {
			mLockPatternView.enableInput();
		} else {
			mLockPatternView.disableInput();
		}

		mLockPatternView.setDisplayMode(DisplayMode.Correct);

		switch (mUiStage) {
		case Introduction:
			mLockPatternView.clearPattern();
			break;
		case ChoiceTooShort:
			mLockPatternView.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			break;
		case FirstChoiceValid:
			break;
		case NeedToConfirm:
			mLockPatternView.clearPattern();
			break;
		case ConfirmWrong:
			mLockPatternView.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			break;
		case ChoiceConfirmed:
			saveChosenPatternAndFinish();
			break;
		}

	}

	// clear the wrong pattern unless they have started a new one
	// already
	private void postClearPatternRunnable() {
		mLockPatternView.removeCallbacks(mClearPatternRunnable);
		mLockPatternView.postDelayed(mClearPatternRunnable, 1000);
	}

	private void saveChosenPatternAndFinish() {

		AppMarketApplication.getLockPatternUtils().saveLockPattern(mChosenPattern);
		showToast("密码设置成功");
		setResult(RESULT_OK);
		finish();
	}

	private void showToast(CharSequence message) {
		if (null == mToast) {
			mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		} else {
			mToast.setText(message);
		}
		mToast.show();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}
